package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class Usercontroller {
    @Autowired
    private UserService userservice;

    @Autowired
    private EmailUtil emailUtil;
// http://localhost:8081/selectAllUser
    @GetMapping("/selectAllUser")
    public Result selectAllUser() {

        return Result.success(userservice.findAllUser());
    }
    //添加 用户
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        return Result.success(userservice.registerUser(user));
    }

   // http://localhost:8081/login?username=admin&password=123456
    @PostMapping("/login")
    public Result login(String username, String password) {
        User user = userservice.login(username, password);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

//http://localhost:8081/register
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        try {
            userservice.registerUser(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    // 查询邮箱号是否存在
    // http://localhost:8081/check-email?email=1412425283@qq.com
    @GetMapping("/check-email")
    public Result checkEmail(@RequestParam String email) {
        User user = userservice.findUserByEmail(email);
        if (user != null) {
            return Result.success("邮箱号已存在");
        } else {
            return Result.success("邮箱号不存在");
        }
    }
//http://localhost:8081/sendEmailCode?email=1412425283@qq.com
    //发送邮箱验证码
    @GetMapping("/sendEmailCode")
    public Result sendEmailCode(String email){
        User user = userservice.findUserByEmail(email);
        if (user!= null){
            userservice.sendEmailCode(email);
            return Result.success("发送成功");
        }
        return Result.error("邮箱号不存在");
    }
//http://localhost:8081/reset-password?email=1412425283@qq.com&code=123456&newPassword=123456
    @PostMapping("/reset-password")
    public Result resetPassword(@RequestParam String email,
                                @RequestParam String code,
                                @RequestParam String newPassword) {
        // 验证验证码
        boolean checkCode = userservice.checkCode(email, code);
        if (!checkCode) {
            return Result.error("验证码错误");
        }

        try {
            // 修改密码
            userservice.updatePasswordByEmail(email, newPassword);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }
}